package com.ushine.web.config;

import com.baomidou.mybatisplus.core.handlers.MetaObjectHandler;
import com.ushine.web.base.model.system.UserDO;
import com.ushine.web.security.utils.SecurityUtils;
import org.apache.ibatis.reflection.MetaObject;
import org.springframework.stereotype.Component;

import java.time.LocalDateTime;
import java.util.Date;

/**
 * @Author: yls
 * @Date: 2020/8/25 16:08
 * @Description: mybatis-plus的填充字段
 * @Version 1.0
 */
@Component
public class MybatisMetaHandler implements MetaObjectHandler {

    /**
     * 功能描述:
     * 〈insert（添加数据）：需要自动填充的字段〉
     *
     * @param metaObject 数据对象
     * @return : void
     * @author : yls
     * @date : 2020/10/16 13:58
     */
    @Override
    public void insertFill(MetaObject metaObject) {
        UserDO user = SecurityUtils.getUser();
        String username = "";
        Long userId = 0L;
        if (user != null) {
            username = user.getUsername();
            userId = user.getId();
        }
        this.strictInsertFill(metaObject, "createTime", Date.class, new Date());
        this.strictInsertFill(metaObject, "createUserName", String.class, username);
        this.strictInsertFill(metaObject, "createUserId", Long.class, userId);
        this.strictInsertFill(metaObject, "lastUpdateTime", Date.class, new Date());
        this.strictInsertFill(metaObject, "lastUpdateUser", String.class, username);
        this.strictInsertFill(metaObject, "deleted", LocalDateTime.class, null);
    }

    /**
     * 功能描述:
     * 〈update（更新数据）：需要自动填充的字段〉
     *
     * @param metaObject 数据对象
     * @return : void
     * @author : yls
     * @date : 2020/10/16 13:58
     */
    @Override
    public void updateFill(MetaObject metaObject) {
        String username = SecurityUtils.getUsername();

        this.strictUpdateFill(metaObject, "lastUpdateTime", Date.class, new Date());
        this.strictUpdateFill(metaObject, "lastUpdateUser", String.class, username);
    }
}
